package com.gitee.sop.sopauth.controller;

import com.gitee.sop.sopauth.auth.*;
import com.i72.basic.CacheHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author jiangj
 * @version 1.0.0
 * @ClassName AccessTokenController.java
 * @Description TODO
 * @createTime 2022年01月16日 10:49:00
 */
@Controller
@RequestMapping("token")
public class AccessTokenController {
    @Autowired
    private AccessTokenService accessTokenService;
    @RequestMapping("get")
    @ResponseBody
    public String getAccessToken(@RequestBody FetchTokenParam param){

        //client_credentials
        /*FetchTokenParam param=new FetchTokenParam();

            param.setSecret(secret);
            param.setAppId(appId);
            param.setGrant_type(grant_type);*/
            OAuth2Config config=OAuth2Config.getInstance();
            FetchTokenResult tokenResult = accessTokenService.accessToken(param, config);
            if(tokenResult!=null){
                if(StringUtils.isNotEmpty(tokenResult.getApp_auth_token())) {
                    return tokenResult.getApp_auth_token();
                }else {
                    return tokenResult.getError_description();
                }
        }
        //生成
        return null;
    }
    @RequestMapping("check")
    @ResponseBody
    public Boolean checkAccessToken(String token){

        // 获取客户端传递过来的token

        if(org.apache.commons.lang.StringUtils.isBlank(token)){
            return false;
        }
        // TODO: 校验token有效性，可以从redis中读取
        String appId = CacheHelper.cluster.getValue(token);
        return !org.apache.commons.lang.StringUtils.isBlank(appId);
    }

}
